<!-- src/views/student/PositionList.vue -->
<template>
  <div class="position-list">
    <div class="header">
      <el-page-header @back="goBack" title="返回">
        <template #content>
          <span class="title">实习岗位列表</span>
        </template>
      </el-page-header>

      <div class="filters">
        <el-row :gutter="20" class="filter-row">
          <el-col :span="6">
            <el-input
              v-model="searchFilters.keyword"
              placeholder="搜索岗位名称或企业名称"
              clearable
              @clear="resetSearch"
              @keyup.enter="fetchPositions"
            >
              <template #append>
                <el-button icon="Search" @click="fetchPositions" />
              </template>
            </el-input>
          </el-col>

          <el-col :span="4">
            <el-select
              v-model="searchFilters.workType"
              placeholder="工作类型"
              clearable
              @change="fetchPositions"
            >
              <el-option label="全职" :value="1" />
              <el-option label="兼职" :value="2" />
              <el-option label="实习" :value="3" />
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-select
              v-model="searchFilters.location"
              placeholder="工作地点"
              clearable
              @change="fetchPositions"
            >
              <el-option
                v-for="location in locations"
                :key="location"
                :label="location"
                :value="location"
              />
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-select
              v-model="searchFilters.sortBy"
              placeholder="排序方式"
              @change="fetchPositions"
            >
              <el-option label="最新发布" value="createdAt,desc" />
              <el-option label="薪资最高" value="salaryRange,desc" />
              <el-option label=" deadline 最近" value="deadline,asc" />
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-button @click="resetFilters">重置筛选</el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 岗位列表 -->
    <el-table
      :data="positions"
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="companyName" label="企业名称" min-width="150" />
      <el-table-column prop="title" label="岗位名称" min-width="150" />
      <el-table-column prop="department" label="部门" min-width="100" />
      <el-table-column prop="workLocation" label="工作地点" min-width="100" />
      <el-table-column prop="salaryRange" label="薪资范围" min-width="120" />
      <el-table-column prop="workType" label="工作类型" min-width="100">
        <template #default="scope">
          {{ getWorkTypeLabel(scope.row.workType) }}
        </template>
      </el-table-column>
      <el-table-column prop="recruitmentCount" label="招聘人数" min-width="100" />
      <el-table-column prop="deadline" label="截止日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.deadline) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="viewPositionDetail(scope.row)">查看详情</el-button>
          <el-button
            size="small"
            type="primary"
            @click="applyForPosition(scope.row)"
            :disabled="isDeadlinePassed(scope.row.deadline)"
          >
            {{ getApplyButtonText(scope.row) }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: center;"
    />

    <!-- 岗位详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="selectedPosition.title"
      width="70%"
      class="position-detail-dialog"
    >
      <div v-if="selectedPosition" class="position-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业名称">{{ selectedPosition.companyName }}</el-descriptions-item>
          <el-descriptions-item label="岗位名称">{{ selectedPosition.title }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ selectedPosition.department }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ selectedPosition.workLocation }}</el-descriptions-item>
          <el-descriptions-item label="薪资范围">{{ selectedPosition.salaryRange }}</el-descriptions-item>
          <el-descriptions-item label="工作类型">{{ getWorkTypeLabel(selectedPosition.workType) }}</el-descriptions-item>
          <el-descriptions-item label="招聘人数">{{ selectedPosition.recruitmentCount }}</el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ formatDate(selectedPosition.deadline) }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ formatDate(selectedPosition.createdAt) }}</el-descriptions-item>
        </el-descriptions>

        <div class="description-section">
          <h3>岗位描述</h3>
          <div v-html="selectedPosition.description || '暂无描述'" class="html-content"></div>
        </div>

        <div class="requirements-section">
          <h3>岗位要求</h3>
          <div v-html="selectedPosition.requirements || '暂无要求'" class="html-content"></div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="applyForPosition(selectedPosition)"
            :disabled="isDeadlinePassed(selectedPosition.deadline)"
          >
            {{ getApplyButtonText(selectedPosition) }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useStudentStore } from '../../store/student'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { commonApi } from '../../api/common'

const studentStore = useStudentStore()
const router = useRouter()

const positions = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const selectedPosition = ref({})
const locations = ref([])

// 搜索过滤条件
const searchFilters = reactive({
  keyword: '',
  workType: null,
  location: '',
  sortBy: 'createdAt,desc'
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取岗位列表
const fetchPositions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize,
      keyword: searchFilters.keyword,
      workType: searchFilters.workType,
      workLocation: searchFilters.location
    }

    if (searchFilters.sortBy) {
      const [property, direction] = searchFilters.sortBy.split(',')
      params.sort = `${property},${direction}`
    }

    const response = await commonApi.getAllPositions(params)
    // 过滤掉status为0的岗位
    const filteredPositions = (response.data.content || []).filter(position => position.status !== 0)
    positions.value = filteredPositions
    pagination.total = response.data.totalElements || 0

    // 提取所有不同的工作地点
    const allLocations = [...new Set(positions.value.map(p => p.workLocation).filter(Boolean))]
    locations.value = allLocations

  } catch (error) {
    ElMessage.error('获取岗位列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查看岗位详情
const viewPositionDetail = async (position) => {
  try {
    const response = await commonApi.getPositionDetail(position.id)
    selectedPosition.value = response.data
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取岗位详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 申请岗位
const applyForPosition = (position) => {
  router.push(`/student/apply/${position.id}`)
}

// 检查是否已过截止日期
const isDeadlinePassed = (deadline) => {
  if (!deadline) return false
  return new Date(deadline) < new Date()
}

// 获取申请按钮文本
const getApplyButtonText = (position) => {
  if (isDeadlinePassed(position.deadline)) return '已截止'
  return '申请岗位'
}

// 获取工作类型标签
const getWorkTypeLabel = (workType) => {
  switch (workType) {
    case 1: return '全职'
    case 2: return '兼职'
    case 3: return '实习'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 分页事件处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchPositions()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchPositions()
}

// 返回上一级
const goBack = () => {
  router.go(-1)
}

// 重置搜索
const resetSearch = () => {
  searchFilters.keyword = ''
  fetchPositions()
}

// 重置所有筛选条件
const resetFilters = () => {
  searchFilters.keyword = ''
  searchFilters.workType = null
  searchFilters.location = ''
  searchFilters.sortBy = 'createdAt,desc'
  fetchPositions()
}

onMounted(() => {
  fetchPositions()
})
</script>

<style scoped>
.position-list {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.filters {
  margin-top: 20px;
}

.filter-row {
  align-items: center;
}

.position-detail h3 {
  margin: 15px 0 10px 0;
}

.description-section,
.requirements-section {
  margin-top: 15px;
}

.html-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.position-detail-dialog :deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
